<!DOCTYPE html>
<html>
<head>
	<title>Regular Expressions explained</title>
	<meta charset="utf-8">
	<link href="./manual.css" rel="stylesheet" type="text/css">
</head>
<body>
	<div id="container">
		<header>
			<h3>Found at: http://publish.ez.no/article/articleprint/11/</h3>
			<h1>Regular Expressions explained</h1>
			<p class="byline">
				<span>Author: <a href="http://publish.ez.no/article/author/view/26">Jan Borsodi</a></span>
				<span class="page-date">Publishing date: 30.10.2000 18:02</span>
			</p>
		</header>
		<section>
			This article will give you an introduction to the world of <i>regular expressions</i>. I'll start off with explaining what regular expressions are and introduce it's syntax, then some examples with varying complexity and last a list of tools which use <i>regular expressions</i>.
			<p style="color: #f00">
				[Note: Puppy has a regular expression evaluation and learning tool in the Utilities menu]
			</p>
		</section>
		<section>
			<h2>Concept</h2>
			<p>
				A <i>regular expression</i> is a text pattern consisting of a combination of alphanumeric characters and special characters known as metacharacters. A close relative is in fact the <i>wildcard expression</i> which are often used in file management. The pattern is used to match against text strings. The result of a match is either successful or not, however when a match is successful not all of the pattern must match, this is explained later in the article.
			</p>
			<p>
				You'll find that <i>regular expressions</i> are used in three different ways: Regular text match, search and replace and splitting. The latter is basically the same as the reverse match ie. everything the <i>regular expression</i> did not match.
			</p>
			<p>
				<i>Regular expressions</i> are often simply called regexps or RE, but for consistency I'll be referring to it with its full name.
			</p>
			<p>
				Due to the versatility of the <i>regular expression</i> it is widely used in text processing and parsing. UNIX users are probably familiar with them through the use of the programs, <i>grep</i>, <i>sed</i>, <i>awk</i> and <i>ed</i>. Text editors such as <i>(X)Emacs</i> and <i>vi</i> also use them heavily. Probably the most known use of  <i>regular expressions</i> are in the programming language Perl; you'll find that Perl sports the most advanced <i>regular expression</i> implementation to this day.
			</p>
		</section>
		<section>
			<h2>Usage</h2>
			<p>
				Now you're probably wondering why you should bother to learn <i>regular expressions</i>. Well, if you're a normal computer user your benefits from using them are somewhat small; however if you're either a developer or a system administrator you'll find that knowing <i>regular expressions</i> will make your (professional) life so much better.
			</p>
			<p>
				Developers can use them to parse text files, fix up code and other wonders. System administrators can use them to search through logs, automate boring tasks and sniff the network traffic for unauthorized activity.
			</p>
			<p>
				Actually I would go so far as to say it's a crime for a System Administrator not to have <b>any</b> knowledge of <i>regular expressions</i>.
			</p>
		</section>
		<section>
			<h2>Quantifiers</h2>
			<section>
				<p>
					Before I start explaining the syntax you might want to jump to the last page to learn which programs you can use to test out the examples in this article.
				</p>
				<p>
					The contents of an expression are, as explained earlier, a combination of alphanumeric characters and metacharacters. An alphanumeric character is either a letter from the alphabet
					<code>abc</code>
					or a number
					<code>123</code>
				</p>
				<p>
					Actually in the world of regular expressions any character which is not a metacharacter will match itself (often called literal characters), however a lot of the time you're mostly concerned with the alphanumeric characters. A very special character is the backslash <b>\</b>; this turns any metacharacters into literal characters, and alphanumeric characters into a sort of metacharacter or sequence. The metacharacters are:
					<code>\ | ( ) [  {  ^ $ * + ? . &lt; &gt;</code>
					With that said, normal characters don't sound too interesting, so let's jump to our very first meta characters.
				</p>
			</section>
			<section>
				<p>
					The punctuation mark, or dot, <b>.</b> needs explaining first since it often leads to confusion. This character will not, as many might think, match the punctuation in a line, it is instead a special meta character which matches any character. Using this were you wanted to find the end of the line or the decimal in a floating number will lead to strange results. As explained above, you need to backslashify it to get the literal meaning. For instance take this expression
					<code>1.23</code>
					will match the number 1.23 in a text as you might have guessed, but it will also match these next lines:
					<code>
						1x23<br>
						1 23<br>
						1-23
					</code>
					To make the expression <b>only</b> match the floating number we change it to
					<code>1\.23</code>
					Remember this, it's very important. Now with that said we can get the show going.
				</p>
			</section>
			<section>
				<p>
					Two heavily recurring metacharacters are
					<code>* and +</code>
					They are called quantifiers and tells the engine to look for several occurrences of a character; the quantifier always precedes the character at hand. The <b>*</b> character matches zero or more occurrences of the character in a row, the <b>+</b> character is similar but matches one or more.
				</p>
				<p>
					So if you decided to find words which had the character <i>c</i> in it, you might be tempted to write
					<code>c*</code>
					What might come as a surprise to you is that you will find an enormous number of matches, even words with no c in it will match. How so you ask, well the answer is simple. Recall that the <b>*</b> character matches <b>zero</b> or more characters, well that's exactly what you did, zero characters.<br>
					You see in <i>regular expressions</i> you have the possibility to match what is called <b>the empty string</b>, which is simply a string with zero size. This empty string can actually be found in all texts, for instance the word:
					<code>go</code>
					contains three empty strings. They are contained at the position right before the <b>g</b>, in between the <b>g</b> and the <b>o</b> and after the <b>o</b>. And an empty string contains exactly <b>one</b> empty string. At first this might seem like a really silly thing to do but you'll learn later on how this is used in more complex expressions.<br>
					So with this knowledge we might want to change our expression to:
					<code>c+</code>
					and voila we get only words with c in them.
				</p>
			</section>
			<section>
				<p>
					The next metacharacter you'll learn is:
					<code>?</code>
					This simply tells the engine to either match the character or not (zero or one). For instance the expression:
					<code>cows?</code>
					will match any of these lines:
					<code>
						cow<br>
						cows
					</code>
				</p>
			</section>
			<section>
				<p>
					These three metacharacters are simply a specialized scenario for the more generalized quantifier
					<code>{n,m}</code>
					The <b>n</b> and <b>m</b> are respectively the minimum and maximum size for the quantifier. For instance
					<code>{1,5}</code>
					means match one or up to five characters. You can also skip m to allow for infinite match:
					<code>{1,}</code>
					which matches one or more characters. This is exactly what the <b>+</b> character does. So now you see the connection, <b>*</b> is equal to <b>{0,}</b>, <b>+</b> is equal to <b>{1,}</b> and <b>?</b> is equal to <b>{0,1}</b>.<br />
					The last thing you can do with the quantifier is to also skip the comma,
					<code>{5}</code>
					which means to match 5 characters, no more no less.
				</p>
			</section>
		</section>
		<section>
			<h2>Assertions</h2>
			<p>
				The next type of metacharacters are assertions, these will match if a given assertion is true.
			</p>
			<section>
				<p>
					The first pair of assertions are
					<code>^ and $</code>
					which match the beginning of the line and the end of the line. Note that some <i>regular expression</i> implementations allows you to change their behavior so that they will instead match the beginning of the text and the end of the text. These assertions always match a zero length string, or in other words they match a position. For instance if you wrote this expression:
					<code>^The</code>
					it would match any line which began with the word <b>The</b>.
				</p>
			</section>
			<section>
				<p>
					The next assertion characters match at the beginning and end of a word, they are:
					<code>&lt; and &gt;</code>
					they come in handy when you want to match a word precisely, for instance:
					<code>cow</code>
					would match any of the following words:
					<code>
						cow<br>
						coward<br>
						cowage<br>
						cowboy<br>
						cowl
					</code>
					a small change to the expression:
					<code>&lt;cow&gt;</code>
					and you'll only match the word <b>cow</b> in the text.
				</p>
			</section>
			<section>
				<p>
					One last thing to be said is that all literal characters are in fact assertions themselves, the difference between them and the ones above is that literal ones have a size. So for cleanliness' sake we only use the word assertions for those that are zero-width.
				</p>
			</section>
		</section>
		<section>
			<h2>Groups and alternation</h2>
			<p>
				One thing you might have noticed when we explained quantifiers is that they only worked on the character to the left, since this pretty much limits our expressions I'll explain other uses for quantifiers. Quantifiers can also be used on metacharacters, using them on assertions is silly since they are zero-width and matching one, two, three or more of them doesn't do any good. However the grouping and sequence metacharacters are perfect for being quantified. Let's first start with grouping.
			</p>
			<section>
				<p>
					You can form groups, or subexpressions as they are frequently called, by using the begin and end parenthesis characters:
					<code>( and )</code>
					The <b>(</b> starts the subexpression and the <b>)</b> ends it. It is also possible to have one or more subexpressions inside a subexpressions. The subexpression will match if the contents match. So mixing this with quantifiers and assertions you can do:
					<code>( ?ho)+</code>
					which matches all of the following lines:
					<code>
						ho<br>
						ho ho<br>
						ho ho ho<br>
						hohoho
					</code>
					Another use for the subexpressions are to extract a portion of the match if it matches, this is often used in conjunction with sequences which is discussed later.
				</p>
				<p>
					You can also use the result of a subexpression for what is called a back reference. A back reference is given by using a backslashified digit, only a single non-zero digit, this leaves you with nine back references.<br> matched (except that {article_contents_1} matches a null character). To find the number of the subexpression count the left parentheses from the left.
				</p>
				<p>
					The use for back references are somewhat limited, especially since you only have nine of them, but on some rare occasion you might need it. Note some <i>regular expression</i> implementations can use multi-digit numbers as long as they don't start with a 0.
				</p>
			</section>
			<section>
				<p>
					Next are alternations which allow you to match one of many words; the alternation character is
					<code>|</code>
					a sample usage is:
					<code>Bill|Linus|Steve|Larry</code>
					would match either Bill, Linus, Steve or Larry, and mixing this with subexpressions and quantifiers we can do:
					<code>cow(ard|age|boy|l)?</code>
					which matches any of the following words but none other
					<code>
						cow<br>
						coward<br>
						cowage<br>
						cowboy<br>
						cowl<br>
					</code>
					I mentioned earlier in the article that not all of the expression must match for the match to be successful, this can happen when you're using subexpressions together with alternations. For instance
					<code>((Donald|Dolly) Duck)|(Scrooge McDuck)</code>
					As you see only the left or right top subexpression will match, not both, this is sometimes handy when you want to run a complex pattern in one subexpression and if it fails try another one.
				</p>
			</section>
		</section>
		<section>
			<h2>Sequences</h2>
			<section>
				<p>
					Last we have sequences which define sequences of characters which can match; sometimes you don't want match a word directly but rather something that resembles one. The sequence characters are
					<code>[ and ]</code>
					Any characters put inside the sequence brackets are treated as a literal character, even metacharacters. The only special characters are the <b>-</b> which denotes character ranges and the <b>^</b> which is used to negate a sequence. The sequence is somewhat similar with alternation, the similarity is that only one of the items listed will match. For instance
					<code>[a-z]</code>
					will match any small characters which are in the English alphabet (a to z). Another common sequence is
					<code>[a-zA-Z0-9]</code>
					which matches any small or capital characters in the English alphabet as well as numbers. Sequences are also mixed with quantifiers and assertions to produce more elaborate searches. For instance
					<code>&lt;[a-zA-Z]+&gt;</code>
					matches all whole words. This will match
					<code>
						cow<br>
						Linus<br>
						regular<br>
						expression
					</code>
					but will not match
					<code>
						200<br>
						x-files<br>
						C++
					</code>
				</p>
			</section>
			<section>
				<p>
					Now what if you wanted to find anything but words? The expression
					<code>[^a-zA-Z0-9]+</code>
					would find any sequences of characters which does not contain the English
					alphabet or any numbers.
				</p>
			</section>
			<section>
				<p>
				Some implementations of <i>regular expressions</i> allows you to use
				shorthand versions for commonly used sequences, they are:
				<code>
					\d, a digit [0-9]
					\D, a non-digit [^0-9]<br>
					\w, a word (alphanumeric) [a-zA-Z0-9]<br>
					\W, a non-word [^a-zA-Z0-9]<br>
					\s, a whitespace [ \t\n\r\f]<br>
					\S, a non-whitespace [^ \t\n\r\f]
				</code>
				</p>
			</section>
		</section>
		<section>
			<h2>Wildcards</h2>
			<p>
				For people who have some knowledge with wildcards I'll give a brief explanation on how to convert them to <i>regular expressions</i>. After reading this article you probably have seen the similarities with wildcards. For instance
				<code>*.jpg</code>
				matches any text which end with .jpg. You can also specify brackets with characters, for instance
				<code>*.[ch]pp</code>
				matches any text which ends in .cpp or .hpp. Altogether very similar to regular expressions.
			</p>
			<section>
				<h3>Converting the * operator</h3>
				<p>
					The * means match zero or more of anything in wildcards, as we learned we do this is regular expression with the punctuation mark and the * quantifier. This gives
					<code>.*</code>
					Also remember to convert any punctuation marks from wildcards to be backslashified.
				</p>
			</section>
			<section>
				<h3>Converting the ? operator</h3>
				<p>
					The ? means match any character but do match <b>something</b>, this is exactly what the punctuation mark does.
				</p>
			</section>
			<section>
				<h3>Converting the [] operator</h3>
				<p>
					The square bracket can be used untouched since they have the same meaning going from wildcards to regular expressions.
				</p>
			</section>
			<section>
				<p>
					These leaves us with:<br>
					Replace any * characters with .*<br>
					Replace any ? characters with .<br>
					Leave square brackets as they are.<br>
					Replace any characters which are metacharacters with a backslashified variant.
				</p>
			</section>
			<section>
				<h3>Examples</h3>
				<p>
					<code>*.jpg</code>
					would be converted to
					<code>.*\.jpg</code>
					and
					<code>ez*.[ch]pp</code>
					would be converted to
					<code>ez.*\.[ch]pp</code>
					or alternatively
					<code>ez.*\.(cpp|hpp)</code>
				</p>
			</section>
		</section>
		<section>
			<h2>Examples</h2>
			<p>
				To really get to know <i>regular expressions</i> I've left some commonly used expressions on this page. Study them, experiment and try to understand exactly what they are doing.
			</p>
			<p>
				Email validity, will only match email addresses which are valid, for instance user@host.com
				<code>[a-z0-9_-]+(\.[a-z0-9_-]+)*@[a-z0-9_-]+(\.[a-z0-9_-]+)+</code>
			</p>
			<p>
				Email validity #2, matches email addresses with a name in front, for instance "Joe Doe &lt;user@host.com&gt;"
				<code>("?[a-zA-Z]+"?[ \t]*)+\&lt;[a-z0-9_-]+(\.[a-z0-9_-]+)*@[a-z0-9_-]+(\.[a-z0-9_-]+)+\&gt;</code>
			</p>
			<p>
				Protocol validity, matches web based protocols such as http://, ftp:// or https://
				<code>[a-z]+://</code>
			</p>
			<p>
				C/C++ includes, matches valid include statements in C/C++ files.
				<code>^#include[ \t]+[<"][^>"]+["&gt;]</code>
			</p>
			<p>
				C++ end of line comments
				<code>//.+$</code>
			</p>
			<p>
				C/C++ span line comments, it has one flaw, can you spot it?
				<code>/\*[^*]*\*/</code>
			</p>
			<p>
				Floating point numbers, matches simple floating point numbers of the kind 1.2 and 0.5
				<code>-?[0-9]+\.[0-9]+</code>
			</p>
			<p>
				Hexadecimal numbers, matches C/C++ style hex numbers, 0xcafebabe
				<code>0x[0-9a-fA-F]+</code>
			</p>
		</section>
		<section>
			<h2>Utilities</h2>
			<p>
				There exist several utilities which use regular expressions. I'll leave a list of them with a short description:
			</p>
			<section>
				<h3>grep</h3>
				<p>
					Grep searches named input files for lines containing a match to the given pattern. It can also be used to find files which contains a specific pattern, for instance:
					<code>grep -E "cow|vache" * &gt;/dev/null &amp;&amp; echo "Found a cow"</code>
				</p>
				<p>
					This utility is rather common on Linux distributions, but if you don't have it you can grab a version on <a href="http://www.gnu.org/gnulist/production/grep.html">the GNU page</a>
				</p>
				<p>
					A small tip is to enable extended regular expressions with the options -E, if not, a lot of the metacharacters explained in this article won't work.
				</p>
			</section>
			<section>
				<h3>sed</h3>
				<p>
					Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream.
				</p>
				<p>
					This utility is rather common on Linux distributions, but if you don't have it you can grab a version on <a href="http://www.gnu.org/gnulist/production/sed.html">the GNU page</a>
				</p>
			</section>
			<section>
				<h3>gawk</h3>
				<p>
					Gawk  is  the GNU Project's implementation of the AWK programming language. It conforms to the definition of the language in  the POSIX  1003.2 Command Language And Utilities Standard.
				</p>
				<p>
					This is utility is rather common on Linux distributions, but if you don't have it you can grab a version on <a href="http://www.gnu.org/">the GNU page</a>
				</p>
			</section>
		</section>
		<section>
			<header><i>Regular expression</i> related links:</header>
			<ul>
				<li><a href="http://www.plover.com/~mjd/perl/NPC/index.html">Regular Expressions and NP-Completeness</a></li>
				<li><a href="http://www.cs.rochester.edu/u/leblanc/csc173/fa/re.html">Equivalence of Regular Expressions and Finite Automata</a></li>
				<li><a href="http://virtual.park.uga.edu/humcomp/perl/regex2a.html">Perl Regular Expression Tutorial</a></li>
			</ul>
		</section>
	</div>
</body>
</html>
